package cn.kgc;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 项目名：microservicecloud1
 * 创建人：Junyizm
 * 创建时间：2020/3/12-8:42
 */
public class RoundRule_SZZ extends AbstractLoadBalancerRule {
    private int total=0;//每个服务调用次数，等于5时更换下一个服务
    private int currentIndex=0;//当前服务Index，当达到服务总个数时，要变为0

    //通过算法返回服务
    public Server choose(ILoadBalancer lb, Object key) {
        //如果没有负载策略返回null
        if (lb == null) {
            return null;
        } else {
            //服务对象
            Server server = null;

            while(server == null) {
                //线程挂起返回null
                if (Thread.interrupted()) {
                    return null;
                }

                //获取当前正常服务的实例列表
                List<Server> upList = lb.getReachableServers();
                //获取所有服务
                List<Server> allList = lb.getAllServers();
                //没有服务返回null
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
//                  生成随机数
//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);
                if (total<5){
                    server =upList.get(currentIndex);
                    total++;
                }else{
                    total=0;
                    currentIndex++;
                    if (currentIndex>=upList.size()){
                        currentIndex=0;
                    }
                }

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }

}
